package com.qs.springboot.amqp.direct;

import com.qs.springboot.util.ConnectionUtil;
import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * 消费客户端（exchange类型为direct）
 * <p>
 * 消费者监听绑定routingKey的消息队列，接收发送端发送过来的消息
 * （routingKey和Queue是一起绑定的，也就是说发送端发送消息时候是根据完全匹配routingKey，找到对应的队列，并让消息入队列的）。
 *
 * @author qinyupeng
 * @since 2019-08-05 16:07:14
 */
public class Recv {

    private final static String queue_name = "direct_exchange_queue_test1";
    private final static String exchange_name = "direct_exchange_test";

    public static void main(String[] args) throws IOException, TimeoutException {
        Connection connection = ConnectionUtil.getConnection();
        Channel channel = connection.createChannel();

        channel.queueDeclare(queue_name, false, false, false, null);

        //绑定队列到交换机，同时指定需要订阅的routingKey（也就是说当交换机转发信息包含绑定的routingKey，才会被这个消费者消费）
        channel.queueBind(queue_name, exchange_name, "delete");

        DefaultConsumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String message = new String(body);
                System.out.println("[消费者1] received：" + message);
            }
        };

        //监听队列，自动ack
        channel.basicConsume(queue_name, true, consumer);
    }
}
